import api from './api';
import { Product } from './product.service';
import { orders as mockOrders } from '../mock/data';

export interface Order {
  id: number;
  userId: number;
  orderNumber: string;
  totalAmount: number;
  status: 'pending' | 'paid' | 'cancelled' | 'completed';
  items: OrderItem[];
  paymentMethod?: string;
  paymentId?: string;
  createdAt: string;
  updatedAt: string;
}

export interface OrderItem {
  id: number;
  orderId: number;
  productId: number;
  product: Product;
  quantity: number;
  price: number;
}

export interface OrderListResponse {
  orders: Order[];
  total: number;
  page: number;
  pageSize: number;
}

export interface OrderQueryParams {
  page?: number;
  pageSize?: number;
  status?: 'pending' | 'paid' | 'cancelled' | 'completed';
}

// Mock implementation using local data
export const getOrders = async (params: OrderQueryParams = {}): Promise<OrderListResponse> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 500));
  
  const { page = 1, pageSize = 10, status } = params;
  
  // Filter orders based on status
  let filteredOrders = [...mockOrders];
  
  if (status) {
    filteredOrders = filteredOrders.filter(order => order.status === status);
  }
  
  // Calculate pagination
  const total = filteredOrders.length;
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedOrders = filteredOrders.slice(startIndex, endIndex);
  
  return {
    orders: paginatedOrders,
    total,
    page,
    pageSize,
  };
};

export const getOrderById = async (id: number): Promise<Order> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 300));
  
  const order = mockOrders.find(o => o.id === id);
  
  if (!order) {
    throw new Error('Order not found');
  }
  
  return order;
};

export const payOrder = async (orderId: number, paymentMethod: string): Promise<Order> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 800));
  
  const orderIndex = mockOrders.findIndex(o => o.id === orderId);
  
  if (orderIndex === -1) {
    throw new Error('Order not found');
  }
  
  if (mockOrders[orderIndex].status !== 'pending') {
    throw new Error('Order cannot be paid');
  }
  
  // Update order (in a real app, this would be done on the server)
  const updatedOrder = {
    ...mockOrders[orderIndex],
    status: 'paid' as const,
    paymentMethod,
    paymentId: `P${Date.now()}`,
    updatedAt: new Date().toISOString(),
  };
  
  // Update the mock data (this is just for demo purposes)
  mockOrders[orderIndex] = updatedOrder;
  
  return updatedOrder;
};

export const cancelOrder = async (orderId: number): Promise<Order> => {
  // Simulate API delay
  await new Promise(resolve => setTimeout(resolve, 500));
  
  const orderIndex = mockOrders.findIndex(o => o.id === orderId);
  
  if (orderIndex === -1) {
    throw new Error('Order not found');
  }
  
  if (mockOrders[orderIndex].status !== 'pending') {
    throw new Error('Order cannot be cancelled');
  }
  
  // Update order (in a real app, this would be done on the server)
  const updatedOrder = {
    ...mockOrders[orderIndex],
    status: 'cancelled' as const,
    updatedAt: new Date().toISOString(),
  };
  
  // Update the mock data (this is just for demo purposes)
  mockOrders[orderIndex] = updatedOrder;
  
  return updatedOrder;
}; 